<template>
  <div id="pay-insurance-offer">
    <router-link
      tag="div"
      :to="detailLink"
      class="banner">
      <article>
        <p>车主姓名：{{ owner.name }}</p>
        <p>投保城市：{{ owner.provice }}</p>
        <p>车牌号：<span>{{ owner.plate_num || '未上牌' }}</span></p>
      </article>
      <p>投保方式：{{ insurance_package }}</p>
      <span class="arrow">></span>
    </router-link>

    <grey-header
      title="报价信息"
      v-if="ha.total || astp.total || dh.total || rb.total"
      class="offer-data">
      <p @click="compare">查看对比<span>></span></p>
    </grey-header>

    <header class="tips">投保车若为转保车，依规定需输入验证码才能报价。</header>

    <ul>
      <router-link
        tag="li"
        :to="(ha.jq_check_code || ha.sy_check_code) ? $route.fullPath : confirmLink + '?model_id=' + ha.model_id + '&company_id=1'"
        v-if="+ha.total !== 0 || (ha.jq_check_code || ha.sy_check_code)">
        <h2 class="ha"></h2>
        <h4 class="offer" v-if="+ha.total !== 0">
          <span class="price">{{ ha.total }} 元</span>
          <span class="discount">（{{ ha.total_discount }}折）</span>
        </h4>
        <button v-else-if="ha.jq_check_code || ha.sy_check_code" @click="validateCode('ha')">填写验证码</button>
      </router-link>
      <router-link
        tag="li"
        :to="(astp.jq_check_code || astp.sy_check_code) ? $route.fullPath : confirmLink + '?model_id=' + astp.model_id + '&company_id=2'"
        v-if="+astp.total !== 0 || (astp.jq_check_code || astp.sy_check_code)">
        <h2 class="astp"></h2>
        <h4 class="offer" v-if="+astp.total !== 0">
          <span class="price">{{ astp.total }} 元</span>
          <span class="discount">（{{ astp.total_discount }}折）</span>
        </h4>
        <button v-else-if="astp.jq_check_code || astp.sy_check_code" @click="validateCode('astp')">填写验证码</button>
      </router-link>
      <router-link
        tag="li"
        :to="(dh.jq_check_code || dh.sy_check_code) ? $route.fullPath : confirmLink + '?model_id=' + dh.model_id + '&company_id=3'"
        v-if="+dh.total !== 0 || (dh.jq_check_code || dh.sy_check_code)">
        <h2 class="dh"></h2>
        <h4 class="offer" v-if="+dh.total !== 0">
          <span class="price">{{ dh.total }} 元</span>
          <span class="discount">（{{ dh.total_discount }}折）</span>
        </h4>
        <button v-else-if="dh.jq_check_code || dh.sy_check_code" @click="validateCode('dh')">填写验证码</button>
      </router-link>
      <router-link
        tag="li"
        :to="(rb.jq_check_code || rb.sy_check_code) ? $route.fullPath : confirmLink + '?model_id=' + rb.model_id + '&company_id=4'"
        v-if="+rb.total !== 0 || (rb.jq_check_code || rb.sy_check_code)">
        <h2 class="rb"></h2>
        <h4 class="offer" v-if="+rb.total !== 0">
          <span class="price">{{ rb.total }} 元</span>
          <span class="discount">（{{ rb.total_discount }}折）</span>
        </h4>
        <button v-else-if="rb.jq_check_code || rb.sy_check_code" @click="validateCode('rb')">填写验证码</button>
      </router-link>
      <router-link
        tag="li"
        :to="(bbw.jq_check_code || bbw.sy_check_code) ? $route.fullPath : confirmLink + '?model_id=' + bbw.model_id + '&company_id=5'"
        v-if="+bbw.total !== 0 || (bbw.jq_check_code || bbw.sy_check_code)">
        <h2 class="bbw"></h2>
        <h4 class="offer" v-if="+bbw.total !== 0">
          <span class="price">{{ bbw.total }} 元</span>
          <span class="discount">（{{ bbw.total_discount }}折）</span>
        </h4>
        <button v-else-if="bbw.jq_check_code || bbw.sy_check_code" @click="validateCode('bbw')">填写验证码</button>
      </router-link>
    </ul>

    <p class="message" v-if="(+ha.total === 0 && !ha.jq_check_code && !ha.sy_check_code) &&
                             (+astp.total === 0 && !astp.jq_check_code && !astp.sy_check_code) &&
                             (+dh.total === 0 && !dh.jq_check_code && !dh.sy_check_code) &&
                             (+rb.total === 0 && !rb.jq_check_code && !rb.sy_check_code) &&
                             (+bbw.total === 0 && !bbw.jq_check_code && !bbw.sy_check_code)">
      所有保险公司皆无法处理此保单
    </p>

    <p class="message" v-if="ha.error_msg && ha.error_msg !== '验证码错误'">
      华安：{{ ha.error_msg }}
    </p>

    <p class="message" v-if="astp.error_msg && astp.error_msg !== '验证码错误'">
      安盛天平：{{ astp.error_msg }}
    </p>

    <p class="message" v-if="dh.error_msg && dh.error_msg !== '验证码错误'">
      鼎和：{{ dh.error_msg }}
    </p>

    <p class="message" v-if="rb.error_msg && rb.error_msg !== '验证码错误'">
      中国人民保险：{{ rb.error_msg }}
    </p>

    <p class="message" v-if="bbw.error_msg && bbw.error_msg !== '验证码错误'">
      北部湾保险：{{ bbw.error_msg }}
    </p>

    <div class="public-btn-box">
      <button class="back" @click="$router.go(-1)">取消</button>
      <router-link
        :to="detailLink"
        tag="button"
        class="back">修改投保方案
      </router-link>
    </div>

    <popup
      class="codePopup"
      v-model="codePopupShow"
      pop-transition="popup-fade">
      <h2 :class="codeFromCompany"></h2>

      <p>请输入图中验证码</p>
      <p>不区分大小写</p>

      <section v-if="codeFromCompany && this[codeFromCompany].jq_check_code">
        <div class="code-box">
          <span>交强险</span>
          <img :src="'data:img/jpg;base64,' + this[codeFromCompany].jq_check_code" alt="">
        </div>

        <input
          type="text"
          v-model="jqCode"
          v-validate="'required|alpha_num|max:4|min:4'"
          name="验证码">
        <span v-show="VeeErrors.has('验证码')">{{ VeeErrors.first('验证码') }}</span>
      </section>

      <section v-if="codeFromCompany && this[codeFromCompany].sy_check_code">
        <div class="code-box">
          <span>商业险</span>
          <img :src="'data:img/jpg;base64,' + this[codeFromCompany].sy_check_code" alt="">
        </div>

        <input
          type="text"
          v-model="syCode"
          v-validate="'required|alpha_num|max:4|min:4'"
          name="验证码">
        <span v-show="VeeErrors.has('验证码')">{{ VeeErrors.first('验证码') }}</span>
      </section>

      <div class="public-btn-box">
        <button class="submit" @click="getPriceWithCode(codeFromCompany)">提交</button>
        <button class="back" @click="codePopupShow = false">取消</button>
      </div>
    </popup>
  </div>
</template>

<script>

  import {Popup} from 'mint-ui';
  import GreyHeader from './grey-header.vue';

  export default {
    name: "pay-insurance-offer",
    components: {
      GreyHeader,
      Popup
    },
    data() {
      return {
        owner: {},
        ha: {},
        astp: {},
        dh: {},
        rb: {},
        bbw: {},
        insurance_package: '',
        detailLink: '/fill-insurance-detail/' +
        this.$route.params.type + '/' +
        this.$route.params.car_owner_id + '/' +
        this.$route.params.car_id + '/' +
        this.$route.params.policy_id + '?in_id=' +
        this.$route.params.in_id,

        confirmLink: '/pay-insurance-detail-confirm/' +
        this.$route.params.type + '/' +
        this.$route.params.car_owner_id + '/' +
        this.$route.params.car_id + '/' +
        this.$route.params.policy_id + '/' +
        this.$route.params.in_id,

        // 不可更改
        insurancePriceParams: this.$tool.qs.parse(sessionStorage.getItem('INSURANCE_PRICE_BY_CAR')),

        codeFromCompany: '',
        codePopupShow: false,
        jqCode: '',
        syCode: ''
      }
    },
    methods: {
      compare() {
        this.$router.push({
          name: 'PayInsuranceOfferCompare',
          query: {
            ha_model_id: this.ha.model_id,
            astp_model_id: this.astp.model_id,
            dh_model_id: this.dh.model_id,
            rb_model_id: this.rb.model_id,
            bbw_model_id: this.bbw.model_id
          }
        })
      },

      validateCode(company) {
        this.codeFromCompany = company;
        this.codePopupShow = true;
      },

      getPriceWithCode(company) {
        this.$validator.validateAll().then((result) => {
          if (result) {
            this.codePopupShow = false;

            // 只改变该公司的数字参数
            let _insurancePriceParams = JSON.parse(JSON.stringify(this.insurancePriceParams));
            _insurancePriceParams[company][5] = this.syCode;
            _insurancePriceParams[company][6] = this.jqCode;

            // 构造报价请求需要的函数（同时先验证验证码）

            let _params = {};
            _params[company] = _insurancePriceParams[company];

            this.$http.post({
              api: this.$api.INSURANCE_PRICE_BY_CAR,
              params: _params,
              success: (res) => {

                if (res.data.data[this.codeFromCompany].error_msg === '验证码错误') {

                  this.jqCode = '';
                  this.syCode = '';
                  alert('验证码错误！');

                } else if (!res.data.data[this.codeFromCompany].error_msg) {

                  // 能获取报价
                  // 更新UI（报价/二维码按钮的隐藏，防止刷新更新sessionStorage）

                  let _data = res.data;

                  if (_data.data) {
                    this[company] = _data.data[company];

                    let _allData = this.$tool.qs.parse(sessionStorage.getItem('offer'));
                    _allData.data[company] = _data.data[company];

                    sessionStorage.setItem('offer', this.$tool.qs.stringify(_allData));
                  }
                } else {

                  // 验证码通过，但此公司没有报价

                  alert(res.data.data[this.codeFromCompany].error_msg);

                  // 更新UI（报价/二维码按钮的隐藏，防止刷新更新sessionStorage）

                  let _data = res.data;

                  if (_data.data) {
                    this[company] = _data.data[company];

                    let _allData = this.$tool.qs.parse(sessionStorage.getItem('offer'));
                    _allData.data[company] = _data.data[company];

                    sessionStorage.setItem('offer', this.$tool.qs.stringify(_allData));
                  }
                }
              }
            });
          }
        });
      }
    },
    created() {
      let data = this.$tool.qs.parse(sessionStorage.getItem('offer')),
        insurance_package = this.$route.query.insurance_package;

      if (data.error === '0') {
        this.owner = data.data.people[0];
      }

      if (data.data) {
        if (data.data.ha) {
          this.ha = data.data.ha;
        }
        if (data.data.astp) {
          this.astp = data.data.astp;
        }
        if (data.data.dh) {
          this.dh = data.data.dh;
        }
        if (data.data.rb) {
          this.rb = data.data.rb;
        }
        if (data.data.bbw) {
          this.bbw = data.data.bbw;
        }
      }

      switch (insurance_package) {
        case '1':
          this.insurance_package = '经济型';
          break;
        case '2':
          this.insurance_package = '全面型';
          break;
        case '3':
          this.insurance_package = '豪华型';
          break;
        case '4':
          this.insurance_package = '自定义';
          break;
        default:
          throw 'new type!'
      }
    }
  }
</script>

<style scoped lang="scss">

  #pay-insurance-offer {

    $this-public-padding: 0 1rem;

    .arrow {
      font-size: 3rem;
      color: #999;
    }

    > .banner {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 12rem;
      padding: $this-public-padding;
      background: $white;
      box-shadow: $public-box-shadow;
      border-radius: $public-banner-border-radius;

      > article {
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        max-width: 54%;
        height: $size-as-parent;

        > p {
          font-size: 1.5rem;
          color: #333;

          > span {
            font-weight: bold;
            color: #0196ff;
          }
        }
      }

      > p {
        flex: 1;
        text-align: right;
        font-size: 1.2rem;
        color: #999;
      }
    }

    > .tips {
      height: 3rem;
      line-height: 3rem;
      font-size: 1.2rem;
      color: #fff;
      text-align: center;
      background: #0097ff;
    }

    > .offer-data {
      display: flex;
      justify-content: space-between;

      span {
        padding-left: .6rem;
        font-size: 1.6rem;
      }
    }

    > ul {
      margin-bottom: 1.8rem;

      > li {

        $li-height: 8rem;

        position: relative;
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: $li-height;
        padding: $this-public-padding;
        margin-bottom: .6rem;
        background: $white;

        > .offer {
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          text-align: center;
          height: $size-as-parent;

          > .price {
            font-size: 1.8rem;
            color: #f00;
          }

          > .discount {
            font-size: 1.2rem;
            color: #333;
          }
        }

        button {
          width: 10rem;
          height: 3rem;
          color: $white;
          font-size: 1.5rem;
          background: #0097ff;
          border-radius: 8px;
        }

        &:last-of-type {
          margin-bottom: 0;
        }
      }
    }

    > .message {
      padding: .8rem;
      font-size: 1.2rem;
      color: #f00;
    }

    // todo 公共样式

    > .codePopup {
      text-align: center;
      padding: 2.4rem;

      > p {
        font-size: 1.5rem;
        padding: .6rem;

        &:first-of-type {
          color: #333;
          margin-top: .8rem;
        }

        &:last-of-type {
          color: #999;
        }
      }

      > section {

        $row-height: 4rem;

        position: relative;
        margin-bottom: 1.8rem;

        > .code-box {
          display: flex;
          width: 18rem;
          height: $row-height;
          border: 1px solid #bbb;
          margin-bottom: 1.6rem;

          > span {
            height: $size-as-parent;
            width: 6.8rem;
            font-size: 1.5rem;
            color: #333;
            line-height: $row-height;
            text-align: center;
          }

          > img {
            flex: 1;
            height: $size-as-parent;
          }
        }

        > input {
          width: $size-as-parent;
          height: $row-height;
          padding: .6rem;
          border: 1px solid #bbb;
          border-radius: .6rem;
        }

        > span {
          position: absolute;
          top: $size-as-parent;
          right: 0;
          color: #e4393c;
        }
      }

      > .public-btn-box {
        padding: 0;
        justify-content: space-between;
      }
    }

    h2 {
      display: inline-block;
      width: 108px;
      height: 36px;
      background: url("../../assets/images/public/companies.png") no-repeat center / $size-as-parent auto;

      &.ha {
        background-position-y: 6px;
      }

      &.astp {
        background-position-y: -57px;
      }

      &.dh {
        background-position-y: -118px;
      }

      &.rb {
        background-position-y: -182px;
      }

      &.bbw {
        background-position-y: -250px;
      }
    }
  }
</style>
